package handlers

import (
	"bytes"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
)
var viewPath string
var imgPath string
var web_url string
func init()  {
	viewPath="./app/photo/views"
	imgPath="./app/photo/static"
	web_url="/app/photo/static"
}

func IndexView(w http.ResponseWriter,r *http.Request)  {
	w.Write([]byte("hello"))
}
func Upload(w http.ResponseWriter,r *http.Request)  {
	if r.Method==http.MethodGet{
		w.Write([]byte(loadHtml(viewPath+"/up.html")))
		return
	}
	if r.Method==http.MethodPost{
		f,h,err:=r.FormFile("file")
		if err!=nil{
			w.Write([]byte("文件上传错误:"+err.Error()))
			return ;
		}
		t:=h.Header.Get("Content-type")
		log.Println(t)

		if !strings.Contains(t,"image"){
			io.WriteString(w, "<html><a href=\"/upload\">请上传图片</a><html>")
			return
		}
		os.Mkdir(imgPath, 0666) //项目根路径
		out, err := os.Create(imgPath+"/" + h.Filename)
		if err != nil {
			io.WriteString(w, "文件创建失败："+err.Error())
			return
		}
		_, err = io.Copy(out, f)
		if err != nil {
			io.WriteString(w, "文件保存失败："+err.Error())
			return
		}
		//io.WriteString(w, "/static/"+h.Filename) //web服务器 /
		http.Redirect(w, r, "/detail?name="+h.Filename, 302)
		return

	}

}

func DetailView(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	name := r.Form.Get("name")
	html := loadHtml(viewPath+"/detail.html")
	html = bytes.Replace(html, []byte("@src"), []byte("/image?name="+name), 1)
	w.Write(html)
}
// ImageView 返回指定的图片
func ImageView(w http.ResponseWriter, r *http.Request) {
	r.ParseForm() //把url 或者 form 表单的数据解析到对应的容器 r.From
	name := r.Form.Get("name")
	// fmt.Println(name)
	f, err := os.Open(imgPath +"/"+ name)
	if err != nil {
		w.WriteHeader(404)
		return
	}
	defer f.Close()
	w.Header().Set("Content-Type", "image")
	io.Copy(w, f)
}
func loadHtml(path string)[]byte  {
	var buf []byte

	f,err:=os.Open(path)
	if err!=nil{
		return []byte("error"+err.Error())
	}
	defer f.Close()


	if buf,err=ioutil.ReadAll(f);err!=nil{
		return []byte("read err"+err.Error())
	}
	return buf;

}
func ListView(w http.ResponseWriter, r *http.Request) {
	html := loadHtml(viewPath+"/list.html")
	names, err := ioutil.ReadDir(imgPath)
	if err != nil {
		w.Write([]byte("errors"))
		return
	}
	temp := ""
	for i := 0; i < len(names); i++ {
		temp += `<li><a href="/detail?name=` + names[i].Name() + `"><img src="/image?name=` + names[i].Name() + `" alt="未发现"></a></li>`
	}
	html = bytes.Replace(html, []byte("@html"), []byte(temp), 1)
	w.Write(html)
}